package sixth.group.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import sixth.group.dao.CustomerMapper;
import sixth.group.dao.DishesMapper;
import sixth.group.dao.Ord_dis_matchMapper;
import sixth.group.dao.OrderinfMapper;
import sixth.group.domain.*;
import sixth.group.service.RestaurantService;
import sixth.group.utils.MessageAndData;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;




//应该纳入到Spring容器中管理，但是Controller和用户直接交互，建议分离spring，此例采用spring-mvc
//如何称为一个Controller呢
@Controller
//Controller和用户交互， 用户一般HTTP协议访问Controller，给不同的Controller和不同的方法映射不同的url地址，进行匹配
@RequestMapping(value = "/restaurant")

public class RestaurantController {
    List<Dishes> dishesList=new ArrayList<Dishes>();
    Integer Rid;
    @Autowired
    private RestaurantService restaurantService;
    @Autowired
    private DishesMapper dishesMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private OrderinfMapper orderinfMapper;
    @Autowired
    private Ord_dis_matchMapper ord_dis_matchMapper;

    @RequestMapping(value = "/register")        //拼接结果  应用发布地址+类映射地址+方法映射地址  相当于访问http://localhost:8088/sixth.group_war/restaurant/register时就会匹配这个方法
    public ModelAndView regRestaurant(Restaurant restaurant)
    {
        ModelAndView modelAndView = new ModelAndView();
        boolean b = restaurantService.resRegnew(restaurant);
        System.out.println(b);
        if(b)
        {
            modelAndView.setViewName("redirect:../registersuc.html");
        }
        else {
            modelAndView.setViewName("redirect:../registerfail.html");
        }
        return modelAndView;
    }

    @RequestMapping(value = "/login")
    public ModelAndView logRestaurant(Restaurant restaurant, HttpSession httpSession)
    {
        //ModelAndView对象是Spring封装model和view的通用容器（控制页面跳转）
        ModelAndView modelAndView = new ModelAndView();


        boolean status =restaurantService.resLoginCheck(restaurant);
        if (status)
        {
            //登陆成功
            //Http是一个无状态协议，为了保持通信双方的身份识别，一般采用session(cookie)

            //此时的restaurant只是含有用户名和密码的对象，其他属性并没有值，所以还要通过用户名再从数据库里找到把其他属性补全
            Restaurant restaurant1 = restaurantService.selectwholeinfo(restaurant);

            httpSession.setAttribute("RESTAURANT_SESSION",restaurant1);//把此用户放入session中的RESTAURANT_SESSION属性
            //RESTAURANT_SESSION也可以用来判断登陆状态，判断session中有无此对象

            modelAndView.setViewName("redirect:../restaurant.html");
            //若不加redirect，spring解析器会自动将restaurant.html前面加WEB—INF，后面加.jsp
        }
        else{
            //登陆失败
            modelAndView.setViewName("redirect:../resindex.html");
        }
        return modelAndView;
    }

    @RequestMapping(value = "/listdishes")
    @ResponseBody   //返回给客户端的是jason数据，不跳转页面
    public MessageAndData listDishes(HttpSession httpSession)
    {
        //MessageAndData 是把数据结果封装到对象里，用的时候从对象中取
        Restaurant restaurant = (Restaurant)httpSession.getAttribute("RESTAURANT_SESSION");
        List<Dishes> dishes = restaurantService.checkDishes(restaurant);
        //发送ajax请求，不用切换页面，只用返回数据
        MessageAndData listdishes = MessageAndData.success().add("listdishes",dishes);
        return listdishes;
    }


    @RequestMapping(value = "/getall")
    @ResponseBody
    public MessageAndData listRestautant(HttpSession httpSession)
    {
        //MessageAndData 是把数据结果封装到对象里，用的时候从对象中取
        Restaurant restaurant = (Restaurant)httpSession.getAttribute("RESTAURANT_SESSION");
        List<Restaurant> restaurants = restaurantService.getAllres();
        //发送ajax请求，不用切换页面，只用返回数据
        MessageAndData messageAndData = MessageAndData.success().add("reslist",restaurants);
        return messageAndData;
    }



    @RequestMapping("/list")
    @ResponseBody           //返回给客户端的是json数据
    public MessageAndData list(
            @RequestParam(value = "page",defaultValue = "1")Integer page,
            @RequestParam(value = "pageSize",defaultValue = "5")Integer pageSize
    ){
        PageHelper.startPage(page, pageSize);
        List<Restaurant> restaurants = restaurantService.getAllres();
        //初始化,约束

        //使用pageHelper的方式封装数据
        PageInfo pageInfo = new PageInfo(restaurants);

        return MessageAndData.success().add("pageInfo",pageInfo);
    }

    @RequestMapping("/listdishespage")
    @ResponseBody           //返回给客户端的是json数据
    public MessageAndData listpage(@RequestParam Integer rid,
            @RequestParam(value = "page",defaultValue = "1")Integer page,
            @RequestParam(value = "pageSize",defaultValue = "5")Integer pageSize
    ){

        Restaurant restaurant=restaurantService.selectbyrid(rid);
        PageHelper.startPage(page, pageSize);

        List<Dishes> dishes = restaurantService.checkDishes(restaurant);
        PageInfo pageInfo = new PageInfo(dishes);

//        List<Dishes> dishes = restaurantService.getAllres();
//        //初始化,约束
//
//        //使用pageHelper的方式封装数据
//        PageInfo pageInfo = new PageInfo(restaurants);

        return MessageAndData.success().add("pageInfo",pageInfo);
    }

    @RequestMapping(value = "/display")
    @ResponseBody   //返回给客户端的是jason数据，不跳转页面
    public MessageAndData display(HttpSession httpSession)
    {
        //MessageAndData 是把数据结果封装到对象里，用的时候从对象中取
        Restaurant restaurant = (Restaurant)httpSession.getAttribute("RESTAURANT_SESSION");
        //发送ajax请求，不用切换页面，只用返回数据

        List<String> infos = new ArrayList<>();
        infos.add(0,restaurant.getRusername());
        infos.add(1,restaurant.getRpass());
        infos.add(2,restaurant.getRaddress());
        infos.add(3,restaurant.getRname());
        System.out.println(infos);
        //经测试可以查询到当前登录账户信息
        MessageAndData resinfos = MessageAndData.success().add("resinfos",infos);
        return resinfos;
    }


    @RequestMapping(value = "/changeinfo")
    public ModelAndView changeinfo(Restaurant restaurant, HttpSession httpSession)
    {
        ModelAndView modelAndView = new ModelAndView();
        //先取出来当前登录用户，获取当前rid后赋给传来的带新信息的实体，再根据primarykey更新，最后把session里的信息更新
        Restaurant restaurant1 = (Restaurant)httpSession.getAttribute("RESTAURANT_SESSION");
        restaurant.setRid(restaurant1.getRid());
        boolean b = restaurantService.resChangeInfo(restaurant);
        System.out.println(b);
        Restaurant restaurantnew = restaurantService.selectbyrid(restaurant.getRid());
        httpSession.setAttribute("RESTAURANT_SESSION",restaurantnew);


        //跳到修改成功
        modelAndView.setViewName("redirect:../chgResinfosuc.html");

        return modelAndView;
    }


    @RequestMapping(value = "/adddish")
    @ResponseBody
    public MessageAndData addDish(Integer did,Integer rid,HttpServletResponse response) throws IOException {
        Dishes dishes=dishesMapper.selectByPrimaryKey(did);
        Rid=rid;
        dishesList.add(dishes);

        Integer totalvalue=0;
        for(int i=0;i<dishesList.size();i++){
            totalvalue+=dishesList.get(i).getDvalue();
        }

        MessageAndData messageAndData=MessageAndData.success().add("money",totalvalue);
        return messageAndData;
    }


    @RequestMapping(value = "/createorder")
    public void createOrder(HttpSession httpSession, HttpServletResponse response) throws IOException {
        PrintWriter out = response.getWriter();
        Orderinf orderinf=new Orderinf();
        Customer customer=(Customer) httpSession.getAttribute("Customer");
        orderinf.setOcustomerid(customer.getCid());
        orderinf.setOresaurantid(Rid);
        Integer totalvalue=0;
        for(int i=0;i<dishesList.size();i++){
            totalvalue+=dishesList.get(i).getDvalue();
        }
        orderinf.setOtotalvalue(totalvalue);

        Integer money=customer.getCbalance();
        if(money<totalvalue){
            out.println("<script type='text/javascript'>alert('Money is too less!');window.location.href='../buy.jsp?rid="+Rid+"'</script>");
        }
        else {
            money=money-totalvalue;
            customer.setCbalance(money);
            httpSession.setAttribute("Customer",customer);

            orderinfMapper.insertSelective(orderinf);

            {


                int oid = orderinfMapper.selectByMaxid();

                for (int i = 0; i < dishesList.size(); i++) {
                    Ord_dis_match ord_dis_match = new Ord_dis_match();
                    ord_dis_match.setoDdishesid(dishesList.get(i).getDid());
                    ord_dis_match.setoDorderid(oid);
                    ord_dis_match.setoDquantity(dishesList.size());

                    ord_dis_matchMapper.insertSelective(ord_dis_match);
                }



            }
            customerMapper.updateByPrimaryKeySelective(customer);

            dishesList.clear();

            out.println("<script type='text/javascript'>alert('Create Order success!');window.location.href='../buy.jsp?rid="+Rid+"'</script>");
        }
    }
}
